//
//  YZMOAuthController.swift
//  YZMweibo
//
//  Created by Simon on 16/4/19.
//  Copyright © 2016年 Simon. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking
class YZMOAuthController: UIViewController {
    
    override func loadView() {
        view = webView
        webView.delegate = self
        // 定义一个url
        let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(APPKEY)&redirect_uri=\(REDIRECT_URI)")
        // 定义一个request
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
        
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    // MARK: - 监听方法
    @objc private func cancle(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //自动填充按钮
    @objc private func auto(){
        
        let jsString = "document.getElementById('userId').value='\(CZWeiboName)';document.getElementById('passwd').value='\(CZWeiboPasswd)'"
        // JS注入
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    // MARK: - 设置视图
    private func setupUI(){
        
        view.backgroundColor = UIColor.whiteColor()
        
        setupNav()
    }
    // MARK: - 设置导航栏
    private func setupNav(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancle")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "auto")
       
        navigationItem.title = "微博登陆"
    }
    // MARK: - 懒加载控件
    private lazy var webView: UIWebView = UIWebView()
    
}
// MARK: - webView 代理
extension YZMOAuthController: UIWebViewDelegate{
    
    func webViewDidStartLoad(webView: UIWebView) {
        //SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        //SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        // 判断我们的urlString是否有值
        if let urlString = request.URL?.absoluteString where urlString.hasPrefix(REDIRECT_URI){
            // 判断我们的request 的请求参数是否存在
            if let q = request.URL?.query{
                // 获取code
                let code = q.substringFromIndex("code=".endIndex)
                getUserAccount(code)
                print("成功\(code)")
            }
        }
        
        return true
    }
    
}


extension YZMOAuthController{
    // 请求accessToken
    func getUserAccount(code: String){
        // 请求url
        let urlString = "https://api.weibo.com/oauth2/access_token"
        // 请求参数
        let params = [
            "client_id":APPKEY,
            "client_secret":APPSECRET,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":REDIRECT_URI
            
        ]
        
        YZMNetworkTools.sharedTools.request(YZMRequestMethod.POST, urlString: urlString, params: params) { (response, error) -> () in
            
            if error != nil{
                print(error)
                return
            }
            
            //print("成功\(response)")
            // 在 if let 或者guard 都是对可选值的进行判断 那么 转类型的时候一般都是 '?'
            guard let dataDic = response as? [String: AnyObject] else{
                print("返回的数据不是一个字典")
                return
            }
            
            let account = YZMUserAccount(dict: dataDic)
            
            self.getUserInfo(account)
            
        }
        
    }
    
    func getUserInfo(account: YZMUserAccount){
        // 请求url
        let urlString = "https://api.weibo.com/2/users/show.json"
        // 请求参数
        let params = [
            "access_token":account.access_token!,
            "uid":account.uid!
        ]
        
        YZMNetworkTools.sharedTools.request(YZMRequestMethod.GET, urlString: urlString, params: params) { (response, error) -> () in
            if error != nil{
                print(error)
                return
            }
            
            // 判断可选值
            guard let dataDict = response as? [String: AnyObject] else{
                print("返回的不是一个字典")
                return
            }
            // 对我们的account 的头像和昵称赋值
            account.avatar_large = dataDict["avatar_large"] as? String
            account.screen_name = dataDict["screen_name"] as? String
            // 对用户数据进行保存
            YZMUserAccountTools.sharedTools.saveUserAccount(account)
            
            
            self.dismissViewControllerAnimated(false, completion: { () -> Void in
                // 发送通知告知appdelegate帮我们切换根视图
                NSNotificationCenter.defaultCenter().postNotificationName(SwitchDefaultVcNSNotification, object: nil)
            })
        }
        
      
    }
}


















